package com.yuanfeng.userms.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonStatusEnum;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.dto.userms.BusinessEmployeeDetailDTO;
import com.yuanfeng.commoms.dto.userms.UserTokenBeanDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.*;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.userms.entity.UserBusinessInfoEntity;
import com.yuanfeng.userms.feign.BaseServiceClient;
import com.yuanfeng.userms.mapper.UserBusinessInfoMapper;
import com.yuanfeng.userms.service.UserBusinessInfoService;
import com.yuanfeng.userms.service.UserInfoService;
import com.yuanfeng.userms.vo.BusinessUserInfoVO;
import com.yuanfeng.userms.vo.BusinessUserListVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
*
*/
@Service
public class UserBusinessInfoServiceImpl extends ServiceImpl<UserBusinessInfoMapper, UserBusinessInfoEntity>
implements UserBusinessInfoService{

    private final static Logger log = LoggerFactory.getLogger(UserBusinessInfoServiceImpl.class);

    @Autowired
    private UserBusinessInfoMapper userBusinessInfoMapper;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private BaseServiceClient baseServiceClient;

    @Override
    public ResponseResult isPassedEnt(Map<String, String> map) {
        QueryWrapper<UserBusinessInfoEntity> queryWrapper = new QueryWrapper<>();
        if (null != map && null != map.get("userId")) {
            queryWrapper.eq("user_id", map.get("userId"));
        }
        if (null != map && null != map.get("isApproved")) {
            queryWrapper.eq("is_approved", "1");
        }
        UserBusinessInfoEntity businessInfoEntity = this.baseMapper.selectOne(queryWrapper);

        if(businessInfoEntity!=null){
            return ResponseResult.success(businessInfoEntity);
        }

        return ResponseResult.fail(BizCodeEnume.NO_INFORMATION_OBTAINED.getMsg());

    }

    /**
     * fegin 是否为企业
     *
     * @param userId
     * @return
     */
    @Override
    public boolean isBusinessFegin(String userId) {
        UserBusinessInfoEntity entity = this.baseMapper.selectOne(new LambdaQueryWrapper<UserBusinessInfoEntity>()
                .eq(UserBusinessInfoEntity::getUserId, userId));
        if (entity != null) {
            return entity.getIsApproved() == 1;
        }
        return false;
    }

    @Override
    public ResponseResult isBusiness(Map<String, Object> param) {
        try {
            if (null == param.get("token")) {
                return ResponseResult.fail(BizCodeEnume.TOKEN_IS_NULL);
            }
            String token = (String) param.get("token");
            boolean isExist = RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token);
            if (isExist) {
                UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
                UserBusinessInfoEntity entity=userBusinessInfoMapper.selectOne(new LambdaQueryWrapper<UserBusinessInfoEntity>()
                                              .eq(UserBusinessInfoEntity::getUserId,ui.getUserId())
                                              .eq(UserBusinessInfoEntity::getIsApproved,CommonType.commonStatus.YES.getCode()));
                if(entity!=null){
                    return ResponseResult.success(entity);
                }
                return ResponseResult.fail(0, "不是企业用户");
            } else {
                return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询失败", e);
            return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);

        }
    }


    @Override
    public ResponseResult queryInfo(Map<String, Object> param) {
        ResponseResult result = new ResponseResult();
        try {
            if (null == param.get("token")) {
                result.setCode(CommonStatusEnum.FAIL.getCode());
                result.setMessage(BizCodeEnume.TOKEN_IS_NULL.getMsg());
                return result;
            }
            String token = (String) param.get("token");
            UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
            String userId;
            if (ui != null) {
                // 发送人id
                userId = ui.getUserId();
            } else {
                result.setCode(BizCodeEnume.TOKEN_IS_INVALID.getCode());
                result.setMessage(BizCodeEnume.TOKEN_IS_INVALID.getMsg());
                return result;
            }
            param.put("userId", userId);
            BusinessUserInfoVO detail = userBusinessInfoMapper.queryInfo(param);
            String address = getAddress(detail.getCompanyProvinceId(), detail.getCompanyCityId(), detail.getCompanyDistrictId());
            address = address + detail.getCompanyDetailAddress();
            detail.setCompanyAddress(address);
            result.setCode(CommonStatusEnum.SUCCESS.getCode());
            result.setData(detail);
            result.setMessage(BizCodeEnume.OPERATION_SUCCESSFUL.getMsg());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询失败", e);
            result.setCode(CommonStatusEnum.FAIL.getCode());
            result.setMessage(BizCodeEnume.OPERATION_FAILED.getMsg());
        }

        return result;

    }

    private String getAddress(String provinceId, String cityId, String districtId) {
        if ((provinceId == null || provinceId.equals("")|| provinceId.equals("null"))
                && (cityId == null || cityId.equals("") || cityId.equals("null"))
                && (districtId == null || districtId.equals("") || districtId.equals("null"))) {
            return "";
        }
        String provinceName = baseServiceClient.queryProvinceport(provinceId);
        String cityName = baseServiceClient.queryProvinceport(cityId);
        String districtName = baseServiceClient.queryProvinceport(districtId);
        return provinceName + cityName + districtName;
    }

    @Override
    public ResponseResult queryBusiness(String userId) {

        Map<String, Object> param = new HashMap<>();

        try {
            UserBusinessInfoEntity businessDetail = this.baseMapper.selectOne(new LambdaQueryWrapper<UserBusinessInfoEntity>()
                    .eq(UserBusinessInfoEntity::getUserId, userId));
            if (businessDetail == null) {
                String createUser = userInfoService.getById(userId).getCreateUser();

                businessDetail = this.baseMapper.selectOne(new LambdaQueryWrapper<UserBusinessInfoEntity>()
                        .eq(UserBusinessInfoEntity::getUserId, createUser));
            }
            param = ParseMapUtils.beanToMap(businessDetail);
        } catch (Exception e) {
            return ResponseResult.fail(e.getMessage());
        }

        return ResponseResult.success(param);
    }

    @Override
    public ResponseResult updateBusinessInfo(Map<String, Object> map) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(map.get("token").toString());
        String userId=map.get("userId")==null?userInfo.getUserId():map.get("userId").toString();
        UserBusinessInfoEntity businessInfoEntity = ParseMapUtils.parseMap2Object(map, UserBusinessInfoEntity.class);
        UserBusinessInfoEntity entity=this.baseMapper.selectOne(new LambdaQueryWrapper<UserBusinessInfoEntity>()
                                                  .eq(UserBusinessInfoEntity::getUserId, userId));
        if(businessInfoEntity.getContactNumber().length() != 11){
            return ResponseResult.fail(BizCodeEnume.INCORRECT_PHONE_NUMBER_FORMAT);
        }
        boolean flag;
//        if(entity == null){
//            flag = this.baseMapper.insertBusinessUser(map);
//        }else{
            businessInfoEntity.setId(entity.getId());
            flag = this.baseMapper.updateById(businessInfoEntity)>0;
//        }
        if (flag) {
            return ResponseResult.success(businessInfoEntity);
        } else {
            return ResponseResult.fail(BizCodeEnume.REGISTRATION_FAIL);
        }
    }

    @Override
    public ResponseResult queryList(Map<String, Object> param) {
        IPage<BusinessUserListVO> page=this.baseMapper.queryList(new Query<BusinessUserListVO>().getPage(param),
                param);
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult registerBusiness(Map<String, Object> map) {
        try{
            UserBusinessInfoEntity businessInfoEntity = ParseMapUtils.parseMap2Object(map, UserBusinessInfoEntity.class);
            boolean flag = this.baseMapper.insertBusinessUser(map);
            if (flag) {
                return ResponseResult.success(businessInfoEntity);
            } else {
                return ResponseResult.fail(BizCodeEnume.REGISTRATION_FAIL);
            }
        }catch (Exception e){
            return ResponseResult.fail(e.getMessage());
        }

    }

    @Override
    public ResponseResult queryUserPermissions(UserTokenBeanDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());

        List<Integer> list = new ArrayList<Integer>();
        if (userInfo != null) {
            //获取企业id并判断是否是主账号
            UserBusinessInfoEntity businessInfo = this.baseMapper.selectOne(new LambdaQueryWrapper<UserBusinessInfoEntity>()
                    .eq(UserBusinessInfoEntity::getUserId, userInfo.getUserId()));
            //是否企业:1-是;0-否
            if (businessInfo != null || !userInfo.getIsEmployee().equals(CommonType.commonStatus.YES.getCode())) {
                //主账号获取全部权限
                list = new ArrayList<>(Arrays.asList(CommonType.employeePermissions.PURCHASE_INQUIRY.getCode(),
                        CommonType.employeePermissions.ORGANIZATIONAL.getCode(),
                        CommonType.employeePermissions.CONFIGURATION_PROCESS.getCode(),
                        CommonType.employeePermissions.ACCOUNTING_PERIOD_MANAGEMENT.getCode(),
                        CommonType.employeePermissions.POINTS_MALL.getCode()));
            } else {
                //查找员工权限
                BusinessEmployeeDetailDTO employee = this.baseMapper.queryEmployeeDetail(userInfo.getUserId());
                if (null != employee) {
                    list = ObjectChangeList.castObjToList(JSON.parse(employee.getEmployeePermissions()), Integer.class);
                }
            }
            return ResponseResult.success(list);
        } else {
            return ResponseResult.fail(BizCodeEnume.USER_DOES_NOT_EXIST);
        }
    }

    @Override
    public ResponseResult selectBusinessUser(Map<String, String> paraMap) {
        Integer num = this.baseMapper.selectBusinessUser(paraMap);
        if (num > 0){
            return ResponseResult.fail(0, "该名称已存在");
        }
        return ResponseResult.success("名称不存在");
    }

}
